package com.itqf;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;


/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2021/1/27
 * @Time: 上午10:23
 */
public class ShiroDemo {
    public  static  void  main(String[]args){

        //1.SecurityManager
        Factory<SecurityManager> factory = new  IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();

        //2.设置SecurityManager
        SecurityUtils.setSecurityManager(securityManager);

        //3.得到Subject主体对象
        Subject subject = SecurityUtils.getSubject();

        //4.登录
        //封装AuthenticationToken
        //用户输入的用户名和密码
        //AuthenticationToken token = new UsernamePasswordToken("zhaorenfen","jbgsn");
        //AuthenticationToken token = new UsernamePasswordToken("zhaorenhe","admin");
        AuthenticationToken token = new UsernamePasswordToken("zhaorenhe","jbgsn");

        try {

            subject.login(token);//shiro.ini文件中的对比
            System.out.println("登录成功");
        } catch (UnknownAccountException e) {
            System.out.println("账号不存在");
        }catch (IncorrectCredentialsException e){
            System.out.println("密码错误");
        }catch (AuthenticationException e){
            System.out.println("其他异常");
        }

        System.out.println(subject.isAuthenticated());//true
        System.out.println("-------角色 hasRole()-------");
        System.out.println(subject.hasRole("admin")?"具有admin角色":"不具有admin角色");
        System.out.println(subject.hasRole("developer")?"具有开发者角色":"不具有开发者角色");
        System.out.println(subject.hasRole("saler")?"具有saler角色":"不具有saler角色");
        System.out.println(subject.hasRole("teacher")?"具有teacher角色":"不具有teacher角色");
        System.out.println("-------角色-------");
        System.out.println("-------权限 isPermitted(\"sys:user:*\")-------");
        //admin=sys:user:*,sys:menu:add,shop:goods:*
        System.out.println(subject.isPermitted("sys:user:add")?"具有新增用户的权限":"不具有新增用户的权限");
        System.out.println(subject.isPermitted("sys:user:del")?"具有删除用户的权限":"不具有删除用户的权限");

        System.out.println(subject.isPermitted("sys:menu:add")?"具有新增菜单的权限":"不具有新增菜单的权限");
        System.out.println(subject.isPermitted("sys:menu:del")?"具有删除菜单的权限":"不具有删除菜单的权限");

        System.out.println(subject.isPermitted("shop:order:add")?"具有新增订单的权限":"不具有新增订单的权限");
        System.out.println(subject.isPermitted("shop:order:del")?"具有删除订单的权限":"不具有删除订单的权限");

        System.out.println(subject.isPermitted("shop:goods:add")?"具有新增商品的权限":"不具有新增商品的权限");
        System.out.println(subject.isPermitted("shop:goods:del")?"具有删除商品的权限":"不具有删除商品的权限");


    }

}
